package com.javasea.qrprint.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.javasea.qrprint.lib.TscLibDll;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.*;
import javafx.scene.layout.Pane;
import lombok.extern.slf4j.Slf4j;
import com.javasea.qrprint.entity.Result;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
public class FxImageUtil {

    private static Integer qrPrintDelay;

    /**
     * 进行截图
     */
    public static WritableImage takeSnapShot(Pane pane) {
        SnapshotParameters params = new SnapshotParameters();
        WritableImage snapshot = pane.snapshot(null, null);
        return snapshot;
    }

    public static final int ARGB_BLACK = 0xFF00_0000;
    public static final int ARGB_WHITE = 0xFFFF_FFFF;

    /**
     * 生成二维码图片
     */
    public static WritableImage makeQuadCodeImage(String content, int width, int height) {
        WritableImage writableImage = new WritableImage(width, height);
        PixelWriter pixelWriter = writableImage.getPixelWriter();
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            for (int j = 0; j < height; j++) {
                for (int i = 0; i < width; i++) {
                    if (bitMatrix.get(i, j)) {
                        pixelWriter.setArgb(i, j, ARGB_BLACK);
                    } else {
                        pixelWriter.setArgb(i, j, ARGB_WHITE);
                    }
                }
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return writableImage;
    }

}
